package com.jc.task.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jc.task.service.JobService;
import com.jc.task.service.JobTask;
import com.jc.task.util.RedisUtil;
import org.quartz.CronExpression;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * Created by yaojie.cao on 2017/3/8.
 */
@RestController
public class TaskController {

    private static final Logger logger = LoggerFactory.getLogger(TaskController.class);

    @Autowired
    private JobService jobService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JobTask jobTask;

    /**
     * 查询时间任务
     *
     * @return
     */
    @RequestMapping(value = "/date/searchingKey")
    public JSONObject getDateTask(String searchingKey, Integer page, Integer rows, Integer refresh) {

        List<JSONObject> taskList = redisUtil.getDateAll(searchingKey, refresh == 1 ? true : false);
        //分页
        int start = (page - 1) * rows;
        int end = start + rows;
        if (start > taskList.size()) {
            start = taskList.size() - 1;
        }
        if (end > taskList.size()) {
            end = taskList.size();
        }
        List<JSONObject> subTaskList = taskList.subList(start, end);
        JSONObject resultObject = new JSONObject();
        resultObject.put("List", subTaskList);
        resultObject.put("total", taskList.size());
        return resultObject;
    }

    /**
     * 查询cron表达式任务
     *
     * @return
     */
    @RequestMapping(value = "/cron/searchingKey")
    public JSONObject getCronTask(String searchingKey, Integer page, Integer rows, Integer refresh) {
        List<JSONObject> taskList = redisUtil.getCronAll(searchingKey, refresh == 1 ? true : false);
        //分页
        int start = (page - 1) * rows;
        int end = start + rows;
        if (start > taskList.size()) {
            start = taskList.size() - 1;
        }
        if (end > taskList.size()) {
            end = taskList.size();
        }
        List<JSONObject> subTaskList = taskList.subList(start, end);
        JSONObject resultObject = new JSONObject();
        resultObject.put("List", subTaskList);
        resultObject.put("total", taskList.size());
        return resultObject;
    }

    /**
     * 添加任务
     *
     * @param body
     * @return
     */
    @RequestMapping(value = "/addTask", method = RequestMethod.POST)
    public JSONObject addTask(@RequestBody String body) {
        logger.info("添加任务请求参数:{}", body);
        JSONObject resultJSON = new JSONObject();
        resultJSON.put("code", "1");
        //检查是不是JSON格式的参数
        JSONObject requestBody;
        try {
            requestBody = JSON.parseObject(body);
        } catch (Exception ex) {
            resultJSON.put("msg", "参数错误");
            return resultJSON;
        }
        //检查传入的是 Date还是corn表达式
        Date date = requestBody.getDate("date");
        String cronExpression = requestBody.getString("cronExpression");
        try {
            CronExpression exp = new CronExpression(cronExpression);
            date = null;
        } catch (Exception ex) {
            if (date == null) {
                resultJSON.put("msg", "时间格式不对");
                return resultJSON;
            }
        }

        //检查非空判断
        String description = requestBody.getString("description");
        if (description == null) {
            resultJSON.put("msg", "参数缺少description");
            return resultJSON;
        }
        String url = requestBody.getString("url");
        if (url == null) {
            resultJSON.put("msg", "参数缺少url");
            return resultJSON;
        }
        String bodyParameter = requestBody.getString("bodyParameter");
        if (bodyParameter == null) {
            resultJSON.put("msg", "参数缺少bodyParameter");
            return resultJSON;
        }


        String identityKey = UUID.randomUUID().toString();
        requestBody.put("key", identityKey);
        requestBody.put("createDate", new Date());
        redisUtil.set(identityKey, requestBody.toJSONString());
        try {
            jobService.addJob(jobTask, date, cronExpression, identityKey, description, url, bodyParameter);
        } catch (Exception ex) {
            resultJSON.put("msg", "任务添加异常");
            return resultJSON;
        }
        resultJSON.put("code", "0");
        resultJSON.put("jobKey", identityKey);
        resultJSON.put("msg", "成功加入任务,可以根据jobKey调用/deleteTask删除任务");
        return resultJSON;
    }


    @RequestMapping(value = "/deleteTask")
    public JSONObject deleteJop(@RequestBody String body) {
        JSONObject resultJSON = new JSONObject();
        resultJSON.put("code", "1");
        JSONObject requestJSON = JSON.parseObject(body);
        String jobKey = requestJSON.getString("jobKey");
        if (jobKey == null) {
            resultJSON.put("msg", "jobKey不能为空");
            return resultJSON;
        }
        try {
            String jsonBody = redisUtil.get(jobKey);
            jobService.deleteJob(jobKey);
            resultJSON.put("code", "0");
            resultJSON.put("msg", "删除任务成功");
            resultJSON.put("data", jsonBody);
            logger.info("删除之前的数据:{}", jsonBody);
        } catch (Exception ex) {
            resultJSON.put("msg", ex.getMessage());
        }
        return resultJSON;
    }


    @RequestMapping(value = "/update")
    public JSONObject updateJop(@RequestBody String body) {
        JSONObject addTaskObject = addTask(body);
        if (addTaskObject.getString("code").equals("0")) {
            JSONObject deleteObject = deleteJop(body);
            String data = deleteObject.getString("data");
        }
        return null;
    }


    @RequestMapping(value = "/test")
    public String test() {
        return "SUCCESS";
    }

}
